﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.NetworkInformation;
using System.Text;
using System.Net;

namespace BDSimpleStatus.Models
{
    public static class Checks
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        
        public static void CheckPingAndHttp(ServerCheckModel sc, Uri uri)
        {
            #region ping
            if (sc.CheckPing)
            {
                Ping pingsender = new Ping();
                PingOptions options = new PingOptions(128, true);
                // Create a buffer of 32 bytes of data to be transmitted.
                //                                        bdsimplestatusservercheckaaaaaaa
                byte[] buffer = Encoding.ASCII.GetBytes("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
                int timeout = 120;
                PingReply reply = pingsender.Send(uri.Host, timeout, buffer, options);
                if (reply.Status == IPStatus.Success)
                {
                    sc.Message = string.Format("ping:(time:{0}ms, ttl:{1}ms)", reply.RoundtripTime, reply.Options.Ttl);
                    sc.IsPingOk = true;
                }
                else
                {
                    sc.Message = "ping:(time:--ms, ttl:--ms)";
                    sc.IsPingOk = false;
                    logger.Info("ping for {0} failed.", sc.Name);
                }
            }
            #endregion
            #region http
            if (sc.CheckHttp)
            {
                HttpWebResponse response = null;
                try
                {
                    // create the request
                    HttpWebRequest request = WebRequest.Create(sc.URL) as HttpWebRequest;
                    // instruct the server to return headers only
                    request.Method = "HEAD";
                    // make the connection
                    response = request.GetResponse() as HttpWebResponse;
                    // get the headers
                    //headers = response.Headers;
                    if (response != null)
                    {
                        if (response.StatusCode == HttpStatusCode.OK)
                            sc.IsHttpOk = true;
                        else
                            sc.IsHttpOk = false;
                        sc.Message += string.Format(" head:(length:{0} code:{1})", response.ContentLength, response.StatusCode);
                        response.Close();
                    }
                    else
                    {
                        sc.Message += (" head: Port 80 not open.");
                    }
                    
                }
                catch
                {
                    sc.IsHttpOk = false;
                    sc.Message += " head:(Http Error)";
                    logger.Info("Http status not = OK; {0} result is {1}", sc.Name, response == null ? HttpStatusCode.SeeOther : response.StatusCode);
                }
                finally
                {
                    // make sure the response gets closed
                    //  this avoids leaking connections
                    if (response != null)
                    {
                        response.Close();
                    }
                }
            }
            #endregion
        }

        public static void RunChecksHttp(string url)
        {
            HttpWebResponse response = null;
            try
            {
                // create the request
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                // instruct the server to return headers only
                request.Method = "get";
                // make the connection
                response = request.GetResponse() as HttpWebResponse;
                // get the headers
                //headers = response.Headers;
                //if (response.StatusCode == HttpStatusCode.OK)
                //    sc.IsHttpOk = true;
                //else
                //    sc.IsHttpOk = false;
                response.Close();
            }
            catch (Exception ex)
            {
                logger.ErrorException("Method runChecksHttp exception", ex);
            }
            finally
            {
                // make sure the response gets closed
                //  this avoids leaking connections
                if (response != null)
                {
                    response.Close();
                }
            }


        }
    }
}